package com.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.dao.ItemsDao;
import com.dao.OrdersDao;
import com.entity.Browse;
import com.entity.Goods;
import com.entity.Items;
import com.entity.LoginUser;
import com.entity.Orders;
import com.entity.Product;
import com.entity.ProductRecs;
import com.entity.RatingUser;
import com.entity.Recommend;
import com.entity.Types;
import com.entity.UserRecs;
import com.entity.Users;
import com.service.InsertUserService;
import com.service.RecommendService;
import com.service.UserService;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.entity.Tops;
import com.service.GoodService;
import com.service.TopService;
import com.service.TypeService;
import com.util.PageUtil;

/**
 * 前台相关接口 
 */
@Controller
@RequestMapping("/index")
public class IndexController{
	
	private static final int rows = 16; // 默认每页数量

	@Autowired
	private TopService topService;
	@Autowired
	private GoodService goodService;
	@Autowired
	private TypeService typeService;

    @Autowired
    private InsertUserService insertUser;

    //推荐service
	@Autowired
	private RecommendService recommendService;

    @Autowired
    private OrdersDao orderDao;
    @Autowired
    private ItemsDao itemDao;
	@Autowired
	private UserService userService;


	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpSession session){
		request.setAttribute("flag", 1);
		//dailyTaskJob.test1();
		//查询出当前登录用户推荐商品
		//1.判断用户是否登录
		Users user = (Users) session.getAttribute("user");
		if(user!=null){
			//已登录
			UserRecs userRecs =recommendService.queryByUserId(user.getId());
			//System.out.println(userRecs.getRecs());
			if(userRecs==null){
				userRecs=new UserRecs();
			}
			List<Recommend> recommends =JSONObject.parseArray(userRecs.getRecs(), Recommend.class);
			System.out.println(recommends);

			List<Goods> tops=topService.getListByGoodids(recommends,Tops.TYPE_LARGE, 1, 6);
//			if(tops.size()==0){
//				getUserGood(request);
//			}else{
				request.setAttribute("topUserList", tops);
		//	}

		}else{
         //未登录
			getUserGood(request);
		}
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("top1List", topService.getList(Tops.TYPE_SCROLL, 1, 1));
		request.setAttribute("top2List", topService.getList(Tops.TYPE_LARGE, 1, 6));
		request.setAttribute("top3List", topService.getList(Tops.TYPE_SMALL, 1, 8));
		return "/index/index.jsp";
	}

	private void getUserGood(HttpServletRequest request) {
		UserRecs userRecs =recommendService.queryByUserId(3);
		System.out.println(userRecs.getRecs());
		List<Recommend> recommends =JSONObject.parseArray(userRecs.getRecs(), Recommend.class);
		System.out.println(recommends);

		List<Goods> tops=topService.getListByGoodids(recommends,Tops.TYPE_LARGE, 1, 6);
		request.setAttribute("topUserList", tops);
	}

	/**
	 * 推荐列表
	 * @return
	 */
	@RequestMapping("/top")
	public String tops(int typeid, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request) {
		request.setAttribute("flag", typeid==2 ? 7 : 8);
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("goodList", goodService.getList(typeid, page, rows));
		request.setAttribute("pageTool", PageUtil.getPageTool(request, goodService.getTotal(typeid), page, rows));
		return "/index/goods.jsp";
	}
	
	/**
	 * 商品列表
	 * @return
	 */
	@RequestMapping("/goods")
	public String goods(int typeid, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request){
		request.setAttribute("flag", 2);
		if (typeid > 0) {
			request.setAttribute("type", typeService.get(typeid));
		}
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("goodList", goodService.getListByType(typeid, page, rows));
		request.setAttribute("pageTool", PageUtil.getPageTool(request, goodService.getTotalByType(typeid), page, rows));
		return "/index/goods.jsp";
	}
	
	/**
	 * 商品详情
	 * @return
	 */
	@RequestMapping("/detail")
	public String detail(int goodid, HttpServletRequest request, HttpSession session){
		//进入页面，保留当前时间
		session.setAttribute("start",System.currentTimeMillis());
		session.setAttribute("goods",goodService.get(goodid));
		request.setAttribute("good", goodService.get(goodid));
		//request.setAttribute("typeList", typeService.getList());

		request.setAttribute("flag", 1);
		//查询出当前登录用户推荐商品
		//1.判断用户是否登录
		//Users user = (Users) session.getAttribute("user");

			//已登录
			ProductRecs productRecs =recommendService.queryByGoodId(goodid);
			System.out.println(productRecs.getRecs());
			List<Recommend> recommends =JSONObject.parseArray(productRecs.getRecs(), Recommend.class);
			System.out.println(recommends);

			List<Goods> tops=topService.getListByGoodids(recommends,Tops.TYPE_LARGE, 1, 6);
			request.setAttribute("topUserList", tops);
		    request.setAttribute("typeList", typeService.getList());
		return "/index/detail.jsp";
	}
	
	/**
	 * 搜索
	 * @return
	 */
	@RequestMapping("/search")
	public String search(String name, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request) {
		if (Objects.nonNull(name) && !name.trim().isEmpty()) {
			request.setAttribute("goodList", goodService.getListByName(name, page, rows));
			request.setAttribute("pageTool", PageUtil.getPageTool(request, goodService.getTotalByName(name), page, rows));
		}
		request.setAttribute("typeList", typeService.getList());
		return "/index/goods.jsp";
	}


	@RequestMapping("/web")
	public String web( HttpSession session) {
		//开始时间
		Long start = (Long)session.getAttribute("start");
		//商品信息
		Goods goods=(Goods) session.getAttribute("goods");
		//用户信息
		Users users=(Users) session.getAttribute("user");
		if(users==null){
			//创建一个对象将id设置为0
			users = new Users();
			users.setId(3);
		}
		Long end=System.currentTimeMillis();
		System.out.println(start);
		System.out.println("end"+System.currentTimeMillis());
		//插入数据
      Browse browse= new Browse(goods.getId(),String.valueOf(start),String.valueOf(end),users.getId(),String.valueOf((end-start)),goods.getTypeId());
      goodService.insertBrowse(browse);

		//		if (Objects.nonNull(name) && !name.trim().isEmpty()) {
//			request.setAttribute("goodList", goodService.getListByName(name, page, rows));
//			request.setAttribute("pageTool", PageUtil.getPageTool(request, goodService.getTotalByName(name), page, rows));
//		}
//		request.setAttribute("typeList", typeService.getList());
		return "/index/goods.jsp";
	}
    //同步用户
    @RequestMapping("/insertUser")
    public void insertUser() {

	       //先查询出所有的用户id
       List<RatingUser> users= insertUser.queryByRattingUid();
		List<Users> users1 = new ArrayList<>();
		for (int i = 0; i <users.size() ; i++) {
			Users users2 = new Users();
			users2.setId(users.get(i).getUserId());
			users2.setName("测试用户"+users.get(i).getUserId());
			users2.setPassword("123");
			users2.setPhone("12345");
			users2.setAddress("地址"+users.get(i).getUserId());

			users1.add(users2);
		}
//		for (RatingUser user : users) {
//			Users users2 = new Users();
//			users2.setId(user.getUserId());
//			users2.getUsername()
//
//		}
		//进行批量插入数据
		insertUser.insertUsers(users1);
    }
    //同步商品
	//同步用户
	@RequestMapping("/insertPro")
	public void insertPro() {
		List<Product> products=insertUser.queryPros();
		List<Goods> goods = new ArrayList<>();
		//插入商品数据
		for (int i = 0; i <products.size() ; i++) {
			Goods goods1 = new Goods();
			goods1.setId(products.get(i).getProductId());
			goods1.setName(products.get(i).getName());
			goods1.setImage1(products.get(i).getImageUrl());
			goods1.setImage2(products.get(i).getImageUrl());
			goods1.setCover(products.get(i).getImageUrl());
			goods1.setPrice((int)(Math.random()*90+10));
			goods1.setIntro(products.get(i).getTags());
			goods1.setStock((int)(Math.random()*90+10));
			Types types = new Types();
			Integer type = type(catagories(products.get(i).getCategories()));
			types.setId(type);
			goods1.setType(types);

			goods.add(goods1);


		}
		insertUser.insertPro(goods);

	}

	private String catagories(String categories){
		if(categories.contains("办公")){
			return "办公";
		}else if(categories.contains("图书")){
			return "图书";

		}else if(categories.contains("数码")){
			return "数码";

		}else if(categories.contains("电器")){
			return "电器";

		}else if(categories.contains("美妆个护")){
			return "美妆个护";

		}else{
			return "其他";
		}

	}
    //类别划分

	private Integer type(String categories){


		switch (categories){
			case "办公":
				return 10;
				//break;
			case "数码":
				return 11;
			case "图书":
				return 12;
			case "电器":
				return 13;
			case "美妆个护":
				return 14;
				default:
					return 15;
		}
	}

	//模拟生成订单
    //同步用户
    @RequestMapping("/insertOrder")
    public void insertOrder() {
        //查询所有的商品
        List<Goods> goods=goodService.queryAll();
        //查询所有的用户
        List<RatingUser> users= insertUser.queryByRattingUid();

        //随机生成数量（1-100）
       // int amount = (int)(Math.random()*100+1);
        //随机生成1000条订单
        for (int i = 222; i <322 ; i++) {



            //订单明细
            List<Items> itemsList= new ArrayList<>();
            //订单明细的2-10个数
            int len=(int)(Math.random()*10+3);
            for (int j = 2; j <len ; j++) {
                int amount = (int)(Math.random()*100+1);
                Random rand = new Random();
                //随机取出商品
                Goods good = goods.get(rand.nextInt(goods.size()));
                Items items=new Items();
                //设置订单明细
                items.setOrderId(i);
                items.setGoodId(good.getId());
                items.setPrice(good.getPrice());
                //设置当前商品购买数量
                items.setAmount(amount);
                //插入明细
               itemDao.insert(items);
               //从总量中减去数据
				good.setStock(good.getStock()-amount);
				goodService.update(good);
			//	goodService.get()
                itemsList.add(items);
            }
           Orders orders= new Orders();
            orders.setItemList(itemsList);
           //设置订单id
           orders.setId(i);
           //已支付状态
           orders.setStatus(Orders.STATUS_UNPAY);
           int amount=0;
           int total=0;
           //设置总数
            for (Items items : orders.getItemList()) {
                amount+=(items.getAmount());
                total+=(items.getPrice()*items.getAmount());
            }
            orders.setAmount(amount);
            orders.setTotal(total);
           // orders.setPaytype(byte);
            Random rand2 = new Random();
            //随机取出一个用户
            RatingUser ratingUser=users.get(rand2.nextInt(users.size()));
//            orders.setName("测试用户"+ratingUser.getUserId());
//            orders.setAddress("地址"+ratingUser.getUserId());
//			orders.setPhone("1234567");
            orders.setUserId(ratingUser.getUserId());
            //随机生成时间
            try {
                long randomDate = getRandomDate();
				//插入登录时间
				isLogin(ratingUser, randomDate);
				//  orders.setSystime(randomDate);
               orders.setSystime( new Date(randomDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }

               //  orderDao.insert(orders);
            orderDao.insertOrder(orders);

			System.out.println(orders);
        }


    }

	private void isLogin(RatingUser ratingUser, long randomDate) {
		LoginUser loginUser = new LoginUser();
		loginUser.setIp("192.168.137.1");
		loginUser.setLoginTime(new Date(randomDate));
		loginUser.setUserId(ratingUser.getUserId());
		loginUser.setIsLogin("Y");
		loginUser.setIsAdmin("N");
		loginUser.setUsername("测试用户"+ratingUser.getUserId());
		userService.insertLoginIn(loginUser);
	}

	public static void main(String[] args) throws ParseException {
        long randomDate = getRandomDate();
		//insertOrder();



        //格式化输出日期
            System.out.printf("从1999-11-30 00:00:00到现在的一个随机日期为:%1$tF %1$tT", randomDate);

        }

    private static long getRandomDate() throws ParseException {
        //获取当前时间
        Calendar calendar = Calendar.getInstance();
        long now = calendar.getTimeInMillis();

        //设置指定时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse("2022-01-01 00:00:00");
        Date end = sdf.parse("2022-5-31 00:00:00");
        long before = date.getTime();
        long endtime=end.getTime();
        Random random = new Random();

        //产生long类型指定范围随机数
        return before + (long) (random.nextFloat() * (endtime - before + 1));
    }


}